﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/// <summary>
/// 用于生成各类地方需要使用的唯一标识
/// </summary>
public static class UniqueID
{
    static UInt64 lastSecond = 0;
    static UInt64 index = 0;

    /// <summary>
    /// 在同一秒内重启程序并调用可能造成错误
    /// </summary>        
    public static string Create()
    {
        UInt64 nowSecond = (UInt64)DateTime.Now.Subtract(new DateTime(2020, 1, 1)).TotalSeconds;
        if (lastSecond == nowSecond)
        {
            // 如果上一次生成ID时的秒数和这次一样就增加索引值
            index++;
        }
        else
        {
            // 秒数变了则重置索引
            lastSecond = nowSecond;
            index = 0;
        }

        string uid = string.Format("{0}_{1}", nowSecond, index);
        return uid;
    }
}
